#include "Common.hpp"
#include <unistd.h>

void Usage(const std::string &cmd)
{
    std::cerr << "Usage: " << cmd << " server_ip server_port" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }

    uint16_t server_port = std::stoi(argv[2]);
    std::string server_ip = argv[1];

    // 1.创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "socket error!";
        exit(SOCKET_ERR);
    }

    // 2.connect连接
    InetAddr peer(server_ip, server_port);
    int n = connect(sockfd, peer.NetAddrPtr(), peer.NetAddrLen());
    if (n < 0)
    {
        std::cerr << "connect error!";
        exit(CONNECT_ERR);
    }

    while (true)
    {
        std::string line;
        std::cout << "Please Enter# ";
        std::getline(std::cin, line);

        write(sockfd, line.c_str(), line.size());

        char buffer[1024];
        ssize_t s = read(sockfd, buffer, sizeof(buffer) - 1);
        if (s > 0)
        {
            buffer[s] = 0;
            std::cout << "TcpServer #" << buffer << std::endl;
        }
    }

    return 0;
}